﻿using AntDesign;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Hosting;
using SageKing.CodeGen.SageKingViewEngine;
using SageKing.Studio.Pages.SageKingMessage.component;
using SageKing.Studio.Shared;

namespace SageKing.Studio.Pages.Base;

/// <summary>
/// 代码生成显示
/// </summary>
/// <param name="ShowMessage"></param>
/// <param name="WebHostEnvironment"></param>
/// <param name="_viewEngine"></param>
/// <param name="_defaultViewEngine"></param>
public class CodeEditBoxModal<T, Tatt>(
    IMessageService ShowMessage,
    IWebHostEnvironment WebHostEnvironment,
    IViewEngine _viewEngine)
: ModalCRUDBase<string, CodeEditBox, T, string> 
    where T : SysSageKingMessageBase<Tatt>
    where Tatt : SysSageKingMessageAttributeBase
{
    DefaultViewEngine _defaultViewEngine;

    public Func<long, Task<List<Tatt>>> QueryChildListFunc { get; set; }

    public Func<int, string?> GetTypeDescFunc { get; set; }
    public Action StateHasChanged { get; set; } = () => { };

    #region IModalCRUD
    public IModalCRUD<string, CodeEditBox, T, string> MeCrud => this;
    public string TabTitle { get; set; }
    public string ParentName { get; set; }
    public string Title { get; set; } = "C#实体代码";

    public string OkTitle { get; set; } = "确认";

    public string CancelText { get; set; } = "取消";

    public bool Visible { get; set; } = false;

    public bool Loading { get; set; } = false;
    public string Model { get; set; }
    public CodeEditBox Component { get; set; }
    public Error? Error { get; set; }
    public RenderFragment ModalTemplate { get; set; }

    public Task DeleteData(string row, string parent)
    {
        throw new NotImplementedException();
    }

    public Task EditOnStatusSwitch(string row)
    {
        throw new NotImplementedException();
    }

    public Task HandleOk(MouseEventArgs e)
    {
        Visible = false;
        return Task.CompletedTask;
    }

    public async Task<bool> InitModel(T row)
    {
        Title = $"{TabTitle}->${row.Name}-:>C#实体代码";
        var result = await GenCodeData(row);
        if (result && Component != null)
        {
            await Component.ChangeText(Model);
        }
        StateHasChanged();
        return result;
    }


    #endregion

    async Task<bool> GenCodeData(T row)
    {
        Model = string.Empty;

        var getAttData = await QueryChildListFunc(row.Id);
        if (!getAttData.Any())
        {
            _ = ShowMessage.WarningAsync($"当前消息结构【{row.Name}：{GetTypeDescFunc(row.Type)}】无可用属性，请确认后再试。");
            return false;
        }
        //生输入界面
        _defaultViewEngine = new DefaultViewEngine()
        {
            ClassName = row.Name,
            NameSpace = "SageKing.Contracts.Entity.Template",
            Description = row.Description,
            ColumnList = getAttData.Select(a => new ColumnOuput()
            {
                PropertyName = a.Name,
                ColumnComment = a.Description,
                NetType = a.Type,
            }).ToList()
        };

        var getCacheFile = row.Key.GetTemplateFileName(".cs");
        if (File.Exists(getCacheFile))
        {
            Model = await File.ReadAllTextAsync(getCacheFile);
            return true;
        }

        var templatePath = Path.Combine(WebHostEnvironment.WebRootPath, "Template", "Entity.razor");

        if (!File.Exists(templatePath)) return false;
        var tContent = File.ReadAllText(templatePath);
        Model = await _viewEngine.RunCompileFromCachedAsync(tContent, _defaultViewEngine, builderAction: builder =>
        {
            builder.AddAssemblyReferenceByName("System.Linq");
            builder.AddAssemblyReferenceByName("System.Collections");
            builder.AddAssemblyReferenceByName("SageKing.Core");
            builder.AddUsing("System.Collections.Generic");
            builder.AddUsing("System.Linq");
            builder.AddUsing("SageKing.Core.Contracts");
            builder.AddUsing("SageKing.Core.Extensions");
        });
        await File.WriteAllTextAsync(getCacheFile, Model);
        return true;
    }


    /// <summary>
    /// 清理本地缓存
    /// </summary>
    /// <returns></returns>
    public bool ClearCacheCodeData(T row)
    {
        var reusult = row.Key.ClearTemplateFileName();
        _ = ShowMessage.WarningAsync($"清理代码缓存:{row.Key}" + (reusult ? "成功" : "失败"));
        return reusult;
    }

}
